import json
import os
from flask import Flask, jsonify, request

app = Flask(__name__)


@app.route('/hello', methods=['GET'])
def hello_world():
    return jsonify(message="Hello, World!")


@app.route('/get_score', methods=['POST'])
def get_json():
    directory = os.path.join(app.root_path, './')  # 假设JSON文件存放在项目根目录下的data文件夹中
    file_path = os.path.join(directory, "FeHelper-20240105172012.json")
    try:
        with open(file_path, 'r', encoding='utf-8') as json_file:
            data = json_file.read()
            return data
    except FileNotFoundError:
        return jsonify(error="File not found."), 404


@app.route('/items/', methods=['POST'])
def test_items():
    directory = os.path.join(app.root_path, './')  # 假设JSON文件存放在项目根目录下的data文件夹中
    file_path = os.path.join(directory, "对话返回信息.json")
    try:
        with open(file_path, 'r', encoding='utf-8') as json_file:
            data = json_file.read()
            return data
    except FileNotFoundError:
        return jsonify(error="File not found."), 404


@app.route('/chat_ai/', methods=['POST'])
def test_chat_ai():
    directory = os.path.join(app.root_path, './')  # 假设JSON文件存放在项目根目录下的data文件夹中
    file_path = os.path.join(directory, "test.json")
    try:
        with open(file_path, 'r', encoding='utf-8') as json_file:
            data = json_file.read()
            return data
    except FileNotFoundError:
        return jsonify(error="File not found."), 404


@app.route('/get_json_info/', methods=['GET'])
def get_json_info():
    directory = os.path.join(app.root_path, './')  # 假设JSON文件存放在项目根目录下的data文件夹中
    file_path = os.path.join(directory, "json_info.json")
    try:
        with open(file_path, 'r', encoding='utf-8') as json_file:
            data = json_file.read()
            return data
    except FileNotFoundError:
        return jsonify(error="File not found."), 404


@app.route('/trafficCondition/', methods=['GET'])
def trafficCondition():
    directory = os.path.join(app.root_path, './')  # 假设JSON文件存放在项目根目录下的data文件夹中
    file_path = os.path.join(directory, "trafficCondition.json")
    try:
        with open(file_path, 'r', encoding='utf-8') as json_file:
            data = json_file.read()
            return data
    except FileNotFoundError:
        return jsonify(error="File not found."), 404


@app.route('/ipLocation/', methods=['GET'])
def ipLocation():
    directory = os.path.join(app.root_path, './')  # 假设JSON文件存放在项目根目录下的data文件夹中
    file_path = os.path.join(directory, "ipLocation.json")
    try:
        with open(file_path, 'r', encoding='utf-8') as json_file:
            data = json_file.read()
            return data
    except FileNotFoundError:
        return jsonify(error="File not found."), 404


@app.route('/talk_demo_one', methods=['POST'])
def talk_demo_one():
    # Get the JSON data from the request
    request_data = request.get_json()

    # Check if 'type' is in the request
    if 'type' not in request_data:
        return jsonify(error="Missing 'type' parameter"), 400

    request_type = request_data['type']

    # Define the mapping of types to file names
    file_mapping = {
        'user_info': '用户信息.json',
        'dialog_info': '对话返回信息.json',
        'other_info': '其他信息.json'
        # Add more mappings as needed
    }

    # Check if the requested type exists in the mapping
    if request_type not in file_mapping:
        return jsonify(error=f"Invalid type '{request_type}'"), 400

    # Get the corresponding file name
    file_name = file_mapping[request_type]

    # Construct the full file path
    directory = os.path.join(app.root_path, './')
    file_path = os.path.join(directory, file_name)

    try:
        # Open and read the specific JSON file
        with open(file_path, 'r', encoding='utf-8') as json_file:
            data = json.load(json_file)
            return jsonify(data)

    except FileNotFoundError:
        return jsonify(error=f"File '{file_name}' not found."), 404
    except json.JSONDecodeError:
        return jsonify(error=f"Invalid JSON format in file '{file_name}'"), 500


@app.route('/talk_demo_two', methods=['GET'])
def talk_demo_two():
    # 获取不同的查询参数
    location_type = request.args.get('type', None)
    field = request.args.get('field', None)

    directory = os.path.join(app.root_path, './')
    file_path = os.path.join(directory, "talk_demo_two.json")

    try:
        with open(file_path, 'r', encoding='utf-8') as json_file:
            full_data = json.load(json_file)

            # 根据不同参数返回不同的结果

            # 1. 如果没有任何参数，返回全部数据
            if location_type is None and field is None:
                return jsonify(full_data)

            # 2. 只传入type参数，返回匹配的地区数据
            if location_type and field is None:
                filtered_data = {
                    key: value for key, value in full_data.items()
                    if location_type.lower() in key.lower()
                }
                return jsonify(filtered_data)

            # 3. 传入type和field参数，返回特定地区的特定字段
            if location_type and field:
                result = {}
                for key, value in full_data.items():
                    if location_type.lower() in key.lower():
                        # 如果字段存在，只返回该字段
                        if field in value:
                            result[key] = {field: value[field]}
                        else:
                            return jsonify(error=f"Field '{field}' not found"), 404

                return jsonify(result)

            # 4. 只传入field参数，返回所有数据中包含该字段的项
            if field and location_type is None:
                filtered_data = {
                    key: {field: value[field]}
                    for key, value in full_data.items()
                    if field in value
                }
                return jsonify(filtered_data)

    except FileNotFoundError:
        return jsonify(error="File not found."), 404
    except json.JSONDecodeError:
        return jsonify(error="Invalid JSON file."), 500
    except Exception as e:
        return jsonify(error=str(e)), 500


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=50001, debug=True)

